//
//  XZRuleVC.m
//  Teecloud
//
//  Created by PC on 2018/11/20.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "XZRuleVC.h"
#import "XZRuleCell.h"
#import "XZRuleFootView.h"
#import "ZJPickBaseView.h"
#import "ZJDatePickerView.h"
#import "ZJNormalPickerView.h"
#import "XZRuleView.h"
#import "XZWorkTime.h"
#import "XZMemberList.h"
#import "XZWorkTimeData.h"

#import "XZPunchCardVC.h"
#import "XZRuleMyselfVC.h"
#import "XZLeaveApplyDetailVC.h"
@interface XZRuleVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tabView;
@property (nonatomic, strong) XZWorkTime *model;
@property (nonatomic, strong) UIButton *rightBtn;
@property (nonatomic, strong) UIButton *dateBtn;
@property (nonatomic, copy) NSString *queryDate;//日期
@property (nonatomic, copy) NSString *memberUserId;//成员id
@property (nonatomic, strong) XZRuleView *ruleView;
@end

@implementation XZRuleVC
//视图消失将其隐藏
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.ruleView hide];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"考勤查询";
    self.view.backgroundColor = kWhiteColor;
    //组员
    UIBarButtonItem *signItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightBtn];
    //时间
    NSString *currentDate = [self getCurrentTime];
    self.queryDate = currentDate;
    [self.dateBtn setTitle:currentDate  forState:UIControlStateNormal];
    UIBarButtonItem *dateItem = [[UIBarButtonItem alloc]initWithCustomView:self.dateBtn];
    self.navigationItem.rightBarButtonItems = @[signItem,dateItem];

    [self queryWorkTimeInfo1];
}
#pragma mark - NetWorking
- (void)queryWorkTimeInfo1{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:self.queryDate forKey:@"queryDate"];
    [dict setValue:self.memberUserId forKey:@"memberUserId"];
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=QueryWorkTimeInfo1&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakself.tabView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                XZWorkTime *model = [XZWorkTime mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                self.model = model;
                //下拉列表
                self.ruleView.listData = model.MemberList;
                //无数据暂未图
                if (model.Datas.count == 0) {
                    [weakself.tabView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [self.tabView reloadData];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
#pragma mark - TableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        //有数据再显示出来
        if (self.model.Datas.count > 0) {
            return 1;
        }
        return 0;
    }
    return self.model.Datas.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    kWeakObject(self)
    //唯一标识符 不复用
    NSString *ID = [NSString stringWithFormat:@"%@",indexPath];
    XZRuleCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[XZRuleCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:ID];
    }
    if (indexPath.section == 0) {
        cell.label.text = @"姓名";
        cell.label.tag = 100;
        cell.label.textColor =k333333Color;
    }else{
        XZWorkTimeData *workTimeData = self.model.Datas[indexPath.row];
        cell.label.text = workTimeData.Name;
        cell.label.textColor =k0C80EBColor;
        cell.model = workTimeData;
    }
    cell.titles = self.model.Titles;
    //详情
    cell.ruleCellBlockOne = ^(XZWorkTimeData * _Nonnull model) {
        XZPunchCardVC *punchCardVC = [[XZPunchCardVC alloc]init];
        punchCardVC.memberUserId = model.UserId;
        punchCardVC.groupId = self.groupId;
        punchCardVC.queryDate = self.queryDate;
        [weakself.navigationController pushViewController:punchCardVC animated:true];
    };
    
    //请假实心按钮
    cell.ruleCellLeaveApplyBlock = ^(NSString * _Nonnull leaveApplyId) {
        XZLeaveApplyDetailVC *leaveApplyDetailVC = [[XZLeaveApplyDetailVC alloc]init];
        leaveApplyDetailVC.id = leaveApplyId;
        [weakself.navigationController pushViewController:leaveApplyDetailVC animated:true];
    };
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return SecCellHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    if (indexPath.section == 1) {
        XZWorkTimeData *workTimeData = self.model.Datas[indexPath.row];
        XZRuleMyselfVC *ruleMyselfVC = [[XZRuleMyselfVC alloc]init];
        ruleMyselfVC.memberUserId = workTimeData.UserId;
        ruleMyselfVC.name = workTimeData.Name;
        ruleMyselfVC.type = @"RULE";
        ruleMyselfVC.groupId = self.groupId;
        [self.navigationController pushViewController:ruleMyselfVC animated:true];
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 1) {
        if (self.model.Datas.count > 0) {
            return 40.f;
        }
        return 0.f;
    }
    return 0.f;
}
//footView
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 1) {
        XZRuleFootView *footView = [XZRuleFootView viewFromXib];
        footView.frame = CGRectMake(0, 0, kScreenWidth, 40.f);
        footView.backgroundColor = kWhiteColor;
        return footView;
    }
    return nil;
}
/**
 选择组成员
 隐藏则显示 反之
 @param sender 按钮
 */
- (void)selectListData:(UIButton *)sender{
    UIWindow *rootWindow = [UIApplication sharedApplication].keyWindow;
    for (UIView *view in rootWindow.subviews) {
        if (view == self.ruleView) {
            [self.ruleView hide];
        }else{
            [self.ruleView show];
        }
    }
}
/**
 选择日期
 
 @param sender 按钮
 */
- (void)dateAction:(UIButton *)sender{
    kWeakObject(self)
    [ZJDatePickerView zj_showDatePickerWithTitle:@"请选择日期" dateType:ZJDatePickerModeYMD defaultSelValue:self.queryDate minDate:nil maxDate:nil isAutoSelect:NO lineColor:kDarkGrayColor rowHeight:40 resultBlock:^(NSString *selectValue) {
        [weakself.dateBtn setTitle:selectValue forState:UIControlStateNormal];
        weakself.queryDate = selectValue;
        [weakself queryWorkTimeInfo1];
    } cancelBlock:^{
        
    }];
    
}
/**
 获取当前的日期
 
 @return 日期字符串
 */
- (NSString *)getCurrentTime{
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *currentDate = [dateFormatter stringFromDate:[NSDate date]];
    return currentDate;
}
#pragma mark - Setter
-(UIButton *)rightBtn{
    if (!_rightBtn) {
        _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightBtn.frame = CGRectMake(0, 0, 100, 30);
        [_rightBtn setImage:[UIImage imageNamed:@"down-white-64"] forState:UIControlStateNormal];
        _rightBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
        [_rightBtn setTitle:@"全部组员" forState:UIControlStateNormal];
        [_rightBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
        _rightBtn.titleLabel.font = [UIFont systemFontOfSize: 13.0f];
        _rightBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
        [_rightBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -30, 0, 0)];
        [_rightBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 80, 0, 0)];
        [_rightBtn addTarget:self action:@selector(selectListData:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightBtn;
}
- (UIButton *)dateBtn{
    if (!_dateBtn) {
        _dateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _dateBtn.frame = CGRectMake(0, 0, 100, 30);
        [_dateBtn setImage:[UIImage imageNamed:@"down-white-64"] forState:UIControlStateNormal];
        [_dateBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
        _dateBtn.titleLabel.font = [UIFont systemFontOfSize: 13.0f];
        _dateBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
        [_dateBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -40, 0, 0)];
        [_dateBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 80, 0, 0)];
        [_dateBtn addTarget:self action:@selector(dateAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _dateBtn;
}
- (XZRuleView *)ruleView{
    if (!_ruleView) {
        kWeakObject(self)
        _ruleView =[XZRuleView viewFromXib];
        _ruleView.frame = CGRectMake(0, kNavBarAndStatusBarHeight, DEVICE_WIDTH, DEVICE_HEIGHT);
        _ruleView.backgroundColor = kClearColor;
        _ruleView.ruleViewBlock = ^(XZMemberList * _Nonnull model) {
            weakself.memberUserId = model.UserId;
            [weakself.rightBtn setTitle:model.Name forState:0];
            [weakself queryWorkTimeInfo1];
        };
    }
    return _ruleView;
}
- (UITableView *)tabView{
    if (!_tabView) {
        _tabView = [[UITableView alloc]initWithFrame:CGRectMake(10, 20, DEVICE_WIDTH-20, DEVICE_HEIGHT-kNavBarAndStatusBarHeight-kBottomSafeHeight-20) style:UITableViewStylePlain];
        _tabView.delegate = self;
        _tabView.dataSource = self;
        _tabView.showsVerticalScrollIndicator =false;
        _tabView.separatorStyle =UITableViewCellSeparatorStyleNone;
//        [_tabView registerClass:[XZRuleCell class] forCellReuseIdentifier:SecCellID];
        //上下拉刷新
        _tabView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(queryWorkTimeInfo1)];
        [self.view addSubview:_tabView];
    }
    return _tabView;
}

@end
